//
//  HomeTabViewController.swift
//  ios_swift_demo1
//
//  Created by liutao on 2020/7/10.
//  Copyright © 2020 lt. All rights reserved.
//

import UIKit

class HomeTabViewController: UIViewController {

    private var button:UIButton? = nil
    
   override func viewDidLoad() {
         super.viewDidLoad()
         
         self.view.backgroundColor = UIColor.background
         
         // 创建UIButton实例，设置Button类型
     
         let myBtn = UIButton(type: UIButton.ButtonType.custom)
         // 设置Button位置与尺寸
         myBtn.frame = CGRect(x: 20, y: 200, width: 200, height: 50)
         // 设置Button标题文字与该文字对应的Button状态
         myBtn.setTitle("点击我吧", for: UIControl.State.normal)
         // 设置Button标题文字的颜色及对应的Button状态
         myBtn.setTitleColor(UIColor.white, for: UIControl.State.normal)
         // 设置Button的背景色
         myBtn.backgroundColor = UIColor.purple
         myBtn.addTarget(self, action: #selector(click), for: .touchUpInside)
         // 将创建的Button添加到当前视图
         self.view.addSubview(myBtn)
     }
     
    @objc func click(){
         self.navigationController?.pushViewController(VideoFeedViewController(), animated: true)
     }

    
    
    func download(){
//        let mURLSession = URLSession.init(configuration: .default, delegate: self, delegateQueue: nil)
////        mURLSession.downloadTask(with: URL.init(string: "http://video-haodanku-com.cdn.fudaiapp.com/26d806bfb9e728608ea0d454227dee9a.mp4?attname=1596114428.mp4")!).resume()
//        //保存的名称
//        let timeInterval:TimeInterval = Date().timeIntervalSince1970
//        let saveName = "\(Int(timeInterval)).mp4"
//        //通过Moya进行下载
//        MyServiceProvider.request(.downloadAsset(assetName: "http://video-haodanku-com.cdn.fudaiapp.com/233bb28e2c5ce42cb255721b8a294f24.mp4?attname=1596114428.mp4", saveName: saveName),progress: {
//                progress in
//            //打印下载速度
//            print(progress.progress)
//        }) {
//            result in
//            switch result {
//            case .success:
//                let localLocation: URL = DefaultDownloadDir.appendingPathComponent(saveName)
//
//                print("下载完毕！保存地址：\(localLocation)---\(localLocation.path)")
//            case let .failure(error):
//                print(error)
//            }
//        }
//    }
    

    }

    
}
import UIKit
import Alamofire
 
import MediaPlayer
import AVKit
 
class HomeTabViewController1: UIViewController {
    var videoUrl = "http://gslb.miaopai.com/stream/1UKfVpOmazRYEb4fVejwhgpX~3uIxmHBV~8VCQ__.mp4"
    let pro = UIProgressView()
    var cancelledData : Data?//用于停止下载时,保存已下载的部分
    var downloadRequest:DownloadRequest!//下载请求对象
    var destination:DownloadRequest.DownloadFileDestination!//下载文件的保存路径
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        self.configUI()
        self.loadData()
    }
    
    func configUI() {
        self.navigationItem.title = "下载测试"
        self.view.backgroundColor = UIColor.white
        pro.frame = CGRect.init(x: 50, y: 200, width: 200, height: 50)
        self.view.addSubview(pro)
        
    }
    
    func loadData() {
 
     
        //下载的进度条显示
         Alamofire.download(videoUrl).downloadProgress(queue: DispatchQueue.main) { (progress) in
            self.pro.setProgress(Float(progress.fractionCompleted), animated: true)//下载进度条
        }
        
        //下载存储路径
        self.destination = {_,response in
            let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first
            let fileUrl = documentsUrl?.appendingPathComponent(response.suggestedFilename!)
            return (fileUrl!,[.removePreviousFile, .createIntermediateDirectories] )
        }
        
        self.downloadRequest = Alamofire.download(videoUrl, to: self.destination)
        
        self.downloadRequest.responseData(completionHandler: downloadResponse)
    }
    
    //根据下载状态处理
    func downloadResponse(response:DownloadResponse<Data>){
        switch response.result {
        case .success:
            print("下载完成")
            let alert = UIAlertController.init(title: "提示", message: "下载完成", preferredStyle: .alert)
            
            let okBtn = UIAlertAction.init(title: "确定", style: .default, handler: nil)
            
            alert.addAction(okBtn)
            self.present(alert, animated: true, completion: {
                self.saveVideoUrl(string: (response.destinationURL?.path)!)
//                self.navigationController?.popViewController(animated: true)
            })
            
//            let vc = AVPlayerViewController()
//            vc.player = AVPlayer.init(url: URL.init(fileURLWithPath: (response.destinationURL?.path)!))
//            vc.player?.play()
//            self.present( vc, animated: true) {
//            }
        case .failure:
            self.cancelledData = response.resumeData//意外停止的话,把已下载的数据存储起来
 
        }
    }
 
    //将下载的网络视频保存到相册
    func saveVideoUrl(string:String) {
        if string != ""{
            if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(string){
                UISaveVideoAtPathToSavedPhotosAlbum(string, self, #selector(self.video(videoPath:didFinishSavingWithError:contextInfo:)), nil)
            }
        }
    }
    ///将下载的网络视频保存到相册
    @objc func video(videoPath: String, didFinishSavingWithError error: NSError, contextInfo info: AnyObject) {
 
        if error.code != 0{
            print("保存失败")
            print(error)
        }else{
            print("保存成功")
            let vc = AVPlayerViewController()
            vc.player = AVPlayer.init(url: URL.init(fileURLWithPath: (videoPath)))
            vc.player?.play()
            self.present( vc, animated: true) {
            }
        }
    }
}
    
 
    
